import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useUserStore } from './user'
import {
	reqAddCart,
	reqCartList,
	reqDeleteCartGoods,
	reqCartGoodsAllSelect,
	reqUpdateCartGoodsState,
} from '@/apis/shopCart'

export const useCartStore = defineStore(
	'cart',
	() => {
		/* state */
		// 购物车商品数据
		const cartList = ref([])
		const userStore = useUserStore()
		// 判断用户是否登录
		const isLogin = computed(() => userStore.userInfo.token)

		/* actions */

		// 获取购物车商品列表
		async function getShopCartListData() {
			const res = await reqCartList()
			cartList.value = res.result
		}

		// 添加购物车方法
		async function addCart(data) {
			// 判断用户是否登录
			if (isLogin.value) {
				const { skuId, count } = data
				// 接口 - 加入购物车
				await reqAddCart({ skuId, count })
				ElMessage.success('加入购物车成功')
				// 获取购物车商品列表
				getShopCartListData()
			} else {
				const markObj = cartList.value.find(item => item.skuId === data.skuId)
				if (markObj) {
					// 当前sku已经存在
					markObj.count += data.count
				} else {
					// 当前sku不存在
					cartList.value.push(data)
				}
				ElMessage({
					type: 'success',
					message: '添加购物车成功',
				})
			}
		}

		// 删除购物车中的商品
		async function removeCartGoods(skuId) {
			if (isLogin.value) {
				await reqDeleteCartGoods([skuId])
				ElMessage.success('删除商品成功')
				// 获取购物车商品列表
				getShopCartListData()
			} else {
				cartList.value = cartList.value.filter(item => item.skuId !== skuId)
			}
		}

		// 购物车单选
		async function handlerSingleSelect({ skuId, count }, isSelected) {
			if (isLogin.value) {
				const params = {
					id: skuId,
					selected: isSelected,
					count,
				}
				await reqUpdateCartGoodsState(params)
				getShopCartListData()
			} else {
				const currentItem = cartList.value.find(item => item.skuId === skuId)
				currentItem.selected = isSelected
			}
		}

		// 购物车商品全选/全不选
		async function handlerAllSelect(isSelected) {
			if (isLogin.value) {
				const params = {
					selected: isSelected,
					ids: cartList.value.map(item => item.skuId),
				}
				await reqCartGoodsAllSelect(params)
				getShopCartListData()
			} else {
				cartList.value.forEach(item => {
					item.selected = isSelected
				})
			}
		}

		// 购物车商品数量修改
		async function handlerUpdateCartGoodsCount({ skuId, selected }, count) {
			if (isLogin.value) {
				const params = {
					id: skuId,
					selected,
					count,
				}
				await reqUpdateCartGoodsState(params)
				getShopCartListData()
			} else {
				const currentItem = cartList.value.find(item => item.skuId === skuId)
				currentItem.count = count
			}
		}

		/* getters */
		// 购物车商品数量总和
		const cartGoodsSum = computed(() => {
			return cartList.value.reduce((pre, current) => {
				return pre + current.count
			}, 0)
		})

		// 购物车商品总价
		const cartGoodsPrice = computed(() => {
			return cartList.value.reduce((pre, current) => {
				return pre + current.count * current.price
			}, 0)
		})

		// 购物车商品是否全选
		const isSelectedAll = computed(() => {
			// every：检测数组中所有元素是否都满足指定条件，返回布尔值结果
			return cartList.value.every(item => item.selected) && cartList.value.length > 0
		})

		// 购物车勾选的商品的数量
		const selectedGoodsSum = computed(() => {
			return cartList.value.filter(item => item.selected).reduce((pre, current) => pre + current.count, 0)
		})

		// 购物车勾选的商品的总价
		const selectedGoodsPrice = computed(() => {
			return cartList.value
				.filter(item => item.selected)
				.reduce((pre, current) => pre + current.count * current.price, 0)
		})

		// 清除购物车商品
		function clearCartGoods() {
			cartList.value = []
		}

		return {
			cartList,
			cartGoodsSum,
			cartGoodsPrice,
			isSelectedAll,
			selectedGoodsSum,
			selectedGoodsPrice,
			isLogin,
			addCart,
			removeCartGoods,
			handlerSingleSelect,
			handlerAllSelect,
			clearCartGoods,
			getShopCartListData,
			handlerUpdateCartGoodsCount,
		}
	},
	{
		persist: true,
	},
)
